package cn.gx.kevin.controller;

import cn.gx.kevin.common.ui.AdminControllerHelper;
import cn.gx.kevin.common.utils.MybatisJDBCTypeName;
import cn.gx.kevin.domain.DynamicCountParam;
import cn.gx.kevin.domain.DynamicWhereParam;
import com.alibaba.fastjson.JSONArray;
import cn.gx.kevin.common.annotation.ApiDescript;
import cn.gx.kevin.common.annotation.ApiParams;
import cn.gx.kevin.common.annotation.ApiParamsDesc;
import cn.gx.kevin.common.annotation.ApiReturnDesc;
import cn.gx.kevin.common.ui.AjaxResult;
import cn.gx.kevin.common.ui.ClientButton;
import cn.gx.kevin.domain.Menu;
import cn.gx.kevin.service.IMenuService;
import cn.gx.kevin.controller.ResetfulBaseController;
import cn.gx.kevin.service.IBaseService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.sql.JDBCType;
import java.util.*;

/**
 * Generate by Kevin's CodeBuilder
 **/
@ApiDescript("系统菜单模块")
@Controller
@RequestMapping(value = "/menu")
public class MenuController extends ResetfulBaseController<Menu, String> {

    IMenuService menuService;

    @Resource(name = "menuService")
    @Override
    public void setService(IBaseService<Menu, String> service) {
        this.service = service;
        menuService = (IMenuService)service;
    }

    /*
     * 页面 views/base/entityPath 文件夹路径
     * ***/
    @Override
    public String setPageModelPath(HttpServletRequest request) {
        // TODO Auto-generated method stub
        return "base" + File.separator + entityPath;
    }

    @Override
    @RequestMapping(value = "/page/{pageName}", method = RequestMethod.GET)
    public String page(@PathVariable("pageName") String pageName, HttpServletRequest request) throws Exception {
        if ("tree".equals(pageName)) {
            String pid = request.getParameter("pid");
            JSONArray json = this.queryJson(pid, request);
            request.setAttribute("treeJson", json.toJSONString());
        }else if("form".equals(pageName)){
            String pid = request.getParameter("pid");
            if(StringUtils.isEmpty(pid)){
                pid = "0";
            }
            request.setAttribute("pid",pid);
        }
        return super.page(pageName, request);
    }

    @Override
    @ApiDescript("新增")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult add(HttpServletRequest request) throws Exception {
        return super.add(request);
    }

    @ApiDescript("更新")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public @ResponseBody AjaxResult update(HttpServletRequest request) throws Exception {
        return super.update(request);
    }

    @ApiDescript("删除")
    @ApiParams("{'idList':'id1,id2'}")
    @RequestMapping(value = "/delete")
    public @ResponseBody AjaxResult delete(HttpServletRequest request) throws Exception {
        return super.delete(request);
    }

    @Override
    protected boolean loadDeleteDataForLog(HttpServletRequest request) {
        return true;
    }

    @ApiDescript("分页多条件可排序查询")
    @ApiParams("{'pid:'0',page:1,'pageSize':15,'_col_sort_fieldName':'asc'}")
    @ApiParamsDesc("{pid:'父ID',page:'当前页',pageSize:'页大小',_col_sort_fieldName:'desc/asc，_col_sort_为前缀标志，fieldName为需要排序的字段名'}")
    @RequestMapping(value = "/list")
    public @ResponseBody AjaxResult list(HttpServletRequest request) throws Exception {
        return super.list(request);
    }

    private JSONArray queryJson(String pid, HttpServletRequest request) {

        // DataGrid grid = getDataGridCfg(request);
        //
        // List<ClientButton> buttonlist = grid.getLineButton();
        List<ClientButton> buttonlist = new ArrayList<ClientButton>();
        String nobtn =  request.getParameter("nobtn");
        if(StringUtils.isEmpty(nobtn)){
            buttonlist.add(ClientButton.getDefaultAddBtn());
            buttonlist.add(ClientButton.getDefaultDelBtn());
            buttonlist.add(ClientButton.getDefaultUpdateBtn());
        }
        JSONArray json = new JSONArray();
        try {
            json = menuService.getMenuJsonByPid(pid, buttonlist);
        } catch (Exception e) {
            logger.error("", e);
        }
        return json;
    }

    /** 设置列表查询参数 **/
    @Override
    protected Map<String, Object> setListParams(HttpServletRequest request) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        String pid = request.getParameter("pid");
        params.put("pid", pid);
        String text = request.getParameter("text");
        if(StringUtils.isNotEmpty(text)){
            params.put("text",text);
        }
        return params;
    }

    @Override
    @ApiDescript("菜单json树数据查询")
    @ApiParams("{pid:'0',nobtn:'1'}")
    @ApiParamsDesc("{ pid:'父ID',nobtn:'如果返回的数据中，需要按钮json，则删除这个参数'}")
    @RequestMapping(value = "/query")
    public @ResponseBody AjaxResult query(HttpServletRequest request) throws Exception {
        String pid = request.getParameter("pid");
        if(StringUtils.isEmpty(pid)){
            pid = "0";
        }
        JSONArray json = this.queryJson(pid, request);
        return returnSuccData(json);
    }

    @ApiReturnDesc("{ code: '0正确/1异常',message: '信息',data: '数据对象'}")
    @ApiParamsDesc("{id:'id'}")
    @ApiDescript("根据ID查询数据")
    @ApiParams("{'id':''}")
    @Override
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public @ResponseBody AjaxResult get(String id) throws Exception {
        return super.get(id);
    }


    @ApiReturnDesc("{ code: '0正确/1异常',message: '信息',data: '数据对象'}")
    @ApiParamsDesc("{id:'id','status':'1/0'}")
    @ApiDescript("禁用启用菜单")
    @ApiParams("{id:'id','status':'1/0'}")
    @RequestMapping(value = "/status", method = RequestMethod.POST)
    public @ResponseBody AjaxResult status(String id,Integer status) throws Exception {
        Menu menu = new Menu();
        menu.setId(id);
        menu.setIsEnable(status);
        this.service.update(menu);
        return returnSuccess();
    }



    @ApiReturnDesc("{ code: '0正确/1异常',message: '信息',data: '数据对象'}")
    @ApiParamsDesc("{id:'id'}")
    @ApiDescript("根据任意字段(驼峰命名)参数count统计")
    @ApiParams("{'s':''}")
    @Override
    @RequestMapping(value = "/count", method = RequestMethod.POST)
    public @ResponseBody AjaxResult count(HttpServletRequest request) throws Exception {
        return super.count(request);
    }
    /**
     * count接口采用动态dao，需要重写返回table名称
     * @param request
     * @return
     */
    @Override
    public DynamicCountParam setDynamicCountParams(HttpServletRequest request){
        JSONObject object = AdminControllerHelper.getParamFromEntityRequest(request);
        DynamicCountParam countParam = new DynamicCountParam();
        countParam.setTabelName("t_sys_base_menu");
        LinkedList<DynamicWhereParam> whereValues = new LinkedList<>();
        for(Map.Entry<String,Object> entry : object.entrySet()){
            String field = AdminControllerHelper.javaField2tableField(entry.getKey());
            Object value =  entry.getValue();
            DynamicWhereParam param = new DynamicWhereParam();
            param.setJdbcType(MybatisJDBCTypeName.VARCHAR_NAME);
            param.setSqlOp("=");
            param.setContact("and");
            param.setFieldName(field);
            param.setFieldValue(value);
            whereValues.add(param);
        }
        return countParam;
    }


}
